'use strict';

const Controller = require('egg').Controller;
const sendToWormhole = require('stream-wormhole');
const fs = require('fs');
const path = require('path');

class CommonController extends Controller {

  /*
     * 删除和状态设置
     **/
  async set_status() {
    const ctx = this.ctx;
    let body = { status: 0, message: '操作失败' };
    const act = ctx.request.body.act;
    const id = ctx.request.body.id;
    const type = ctx.request.body.type || '';
    if (!act || !id || !type || ctx.session.admin_id !== 1) {
      body.message = '参数错误';
    } else {
      let res = false;
      switch (type) {
        case 'admin':
        {
          if (id == 1) {
            body.message = '总管理员不能删除';
          } else {
            res = await ctx.model.Admin.destroy({ where: { admin_id: id } });
            await ctx.service.admin.recordDbLog('管理员删除', ctx.model.Admin.getTableName('tableName'), id);
          }
          break;
        }
        case 'log':
          res = await ctx.logModel.Adminlog.destroy({ where: { log_id: id } });
          break;
        case 'errlog':
          res = await ctx.logModel.Errlog.destroy({ where: { id } });
          break;
        case 'role':
        {
          if (id == 1) {
            body.message = '总管理员角色不能删除';
          } else {
            const num = await ctx.model.Admin.count({ where: { role_id: id }, col: [ 'admin_id' ] });
            if (num) {
              body.message = '请先清空所属该角色的管理员';
            } else {
              res = await ctx.model.Adminrole.destroy({ where: { role_id: id } });
              await ctx.service.admin.recordDbLog('管理员角色删除', ctx.model.Admin.getTableName('tableName'), id);
            }
          }
          break;
        }
        case 'menu':
        {
          const num = await ctx.model.Systemmodule.count({ where: { parent_id: id }, col: [ 'mod_id' ] });
          if (num) {
            body.message = '要删除的菜单中含有子项目,请先移动或删除子项目';
          } else {
            res = await ctx.model.Systemmodule.destroy({ where: { mod_id: id } });
          }
          break;
        }
        case 'module':
          res = await ctx.model.Systemmodule.destroy({ where: { mod_id: id } });
          break;
        case 'user':
        {
          const res_arr = await ctx.model.User.update({ statue: 2 }, { where: { id } });
          res = res_arr[0];
          await ctx.service.admin.recordDbLog('用户删除', ctx.model.User.getTableName('tableName'), id);
          break;
        }
        default:
          break;
      }
      if (res) body = { status: 1, message: '操作成功' };
    }

    this.ctx.body = body;
    this.ctx.status = 200;
  }

  /*
     *验证码生成，内容存入session
     **/
  async captcha() {
    const { img, text } = this.ctx.helper.make_capcha();
    this.ctx.session.captcha = text;
    this.ctx.type = 'image/bmp';
    this.ctx.body = img;
    this.ctx.status = 200;
  }

  /*
     * 上传和删除上传的图片
     **/
  async upload() {
    const ctx = this.ctx;
    const method = ctx.request.method;
    if (method === 'POST') {
      const act = ctx.request.body.act || '';
      const file_url = ctx.request.body.filename || '';
      if (act === 'del' && file_url) {
        const file = path.join('app', file_url);
        console.log(file);
        if (fs.existsSync(file)) {
          fs.unlinkSync(file);
        }
      }
      ctx.status = 200;
    } else {
      const func = ctx.request.query.func || '';
      const path = ctx.request.query.path || 'temp';
      const num = ctx.request.query.num || 1;
      const input = ctx.request.query.input;
      const info = {
        num,
        title: '图片上传',
        upload: ctx.helper.pathFor('adcosvup', { savepath: path, pictitle: 'banner', dir: 'images' }),
        size: '4M',
        type: 'jpg,png,gif,jpeg',
        input,
        func: !func ? 'undefined' : func,
      };
      await ctx.render('/admin/public/upload.html', { info });
    }
  }

  /*
     * 保存上传的文件
     **/
  async save_upload() {
    const ctx = this.ctx;
    const type = ctx.request.query.savepath || '';
    const title = ctx.request.query.pictitle || '';
    const dir = ctx.request.query.dir || 'images';
    const parts = ctx.multipart();
    let part;
    let body = { state: 'ERROR:参数错误' };
    while ((part = await parts()) != null) {
      // 如果是数组的话是 filed
      const filename = part.filename;
      let result = false;
      if (filename) {
        try {
          const base_url = path.join('public', 'upload', dir, type, ctx.helper.time_to_date(0, 1)); // 静态资源访问路径
          const system_path = path.join('app', base_url); // 系统的路径
          if (!fs.existsSync(system_path)) {
            ctx.helper.create_dirs(system_path);
          }
          const time = '' + ctx.helper.date_to_time();
          const save_name = ctx.helper.md5(part.filename).slice(0, 5) + time.slice(3, 10) + path.extname(part.filename); // 保存的文件名称
          const writeStream = fs.createWriteStream(path.join(system_path, save_name));
          result = await part.pipe(writeStream);
          if (result) {
            body = {
              url: path.sep + path.join(base_url, save_name),
              state: 'SUCCESS',
              title,
              original: part.filename,
            };
          } else {
            body = { state: 'ERROR:文件保存失败' };
          }
        } catch (err) {
          // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
          await sendToWormhole(part);
          body = { state: 'ERROR:上传失败' };
          throw err;
        }
      }
    }
    ctx.body = body;
    ctx.status = 200;
  }

}

module.exports = CommonController;
